<template>
  <div class="schedule-week-view">
    <!-- 周切换控制栏 -->
    <div class="week-controls">
      <div class="nav-buttons">
        <button class="nav-button" @click="changeWeek(-1)">上一周</button>
        <button class="today-button" @click="goToToday">今天</button>
        <button class="nav-button" @click="changeWeek(1)">下一周</button>
      </div>
      <div class="week-range">{{ weekRangeText }}</div>
    </div>

    <!-- 星期标题 -->
    <div class="week-header">
      <div class="time-label">时间</div>
      <div 
        v-for="(day, index) in weekDays" 
        :key="index" 
        class="day-header"
        :class="{ 'today': day.isToday }"
      >
        <div class="day-name">{{ day.dayName }}</div>
        <div class="day-date">{{ day.date | formatDate }}</div>
      </div>
    </div>

    <!-- 时间网格 -->
    <div class="time-grid">
      <template v-for="hour in timeSlots">
        <div 
          v-for="minute in ['00', '30']" 
          :key="`${hour.value}-${minute}`" 
          class="time-row"
        >
          <div class="time-slot" v-if="minute === '00'">{{ hour.label }}</div>
          <div class="empty-slot" v-else></div>

          <div 
            v-for="(day, dayIndex) in weekDays" 
            :key="`${dayIndex}-${hour.value}-${minute}`" 
            class="grid-cell"
            :class="{ 'today': day.isToday }"
            @click="handleCellClick(day.date, `${hour.value.slice(0,2)}:${minute}`)"
          >
            <ScheduleActions 
              v-for="schedule in getSchedule(day.date, `${hour.value.slice(0,2)}:${minute}`)" 
              :key="String(schedule.scheduleId)"
              :schedule="schedule" 
              @edit="$emit('edit', $event)" 
              @delete="$emit('delete', $event)"
            >
              <div 
                class="schedule-item"
                :style="getScheduleStyle(schedule)"
              >
                <div class="schedule-title">{{ schedule.title }}</div>
                <div class="schedule-time">
                  {{ schedule.startHour }}-{{ schedule.endHour }}
                </div>
              </div>
            </ScheduleActions>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import ScheduleActions from '@/components/Schedule/ScheduleActions.vue'

export default {
  components: { ScheduleActions },
  props: ['schedules'],
  data() {
    return {
      currentWeekOffset: 0,
      titleColors: {}
    }
  },
  
  computed: {
    isMobile() {
      return window.innerWidth <= 768;
    },
    
    timeSlots() {
      const slots = [];
      for (let i = 8; i < 24; i++) {
        slots.push({
          value: `${String(i).padStart(2, '0')}:00`,
          label: `${String(i).padStart(2, '0')}:00`
        });
      }
      return slots;
    },
    
    weekDays() {
      const days = []
      const today = new Date()
      today.setHours(0, 0, 0, 0)

      const startDate = new Date(today)
      const dayOfWeek = today.getDay() === 0 ? 7 : today.getDay()
      startDate.setDate(today.getDate() - dayOfWeek + 1 + (this.currentWeekOffset * 7))

      for (let i = 0; i < 7; i++) {
        const date = new Date(startDate)
        date.setDate(startDate.getDate() + i)

        days.push({
          date: this.formatLocalDate(date),
          dayName: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'][i],
          isToday: date.toDateString() === today.toDateString()
        })
      }

      return days
    },
    
    weekRangeText() {
      if (this.weekDays.length < 7) return ''
      const firstDay = new Date(this.weekDays[0].date)
      const lastDay = new Date(this.weekDays[6].date)

      if (firstDay.getFullYear() === lastDay.getFullYear()) {
        if (firstDay.getMonth() === lastDay.getMonth()) {
          return `${firstDay.getMonth() + 1}月${firstDay.getDate()}日-${lastDay.getDate()}日`
        }
        return `${firstDay.getMonth() + 1}月${firstDay.getDate()}日-${lastDay.getMonth() + 1}月${lastDay.getDate()}日`
      }
      return `${firstDay.getFullYear()}年${firstDay.getMonth() + 1}月${firstDay.getDate()}日-${lastDay.getFullYear()}年${lastDay.getMonth() + 1}月${lastDay.getDate()}日`
    }
  },
  
  filters: {
    formatDate(val) {
      const date = new Date(val)
      return `${date.getMonth() + 1}/${date.getDate()}`
    }
  },
  
  methods: {
    formatLocalDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    timeToMinutes(timeStr) {
      const [hours, minutes] = timeStr.split(':').map(Number)
      return hours * 60 + minutes
    },
    
    getSchedule(date, time) {
      return this.schedules.filter(item => {
        if (item.date !== date) return false;

        const start = this.timeToMinutes(item.startHour);
        const end = this.timeToMinutes(item.endHour);
        const current = this.timeToMinutes(time);

        return start <= current && end > current;
      });
    },
    
    handleCellClick(date, time) {
      this.$emit('cell-click', { date, time })
    },
    
    changeWeek(offset) {
      this.currentWeekOffset += offset
    },
    
    goToToday() {
      this.currentWeekOffset = 0
    },
    
    getColorForTitle(title) {
      if (!this.titleColors[title]) {
        // 为每个标题生成一个随机但稳定的颜色
        const hash = this.hashCode(title);
        const hue = Math.abs(hash) % 360;
        this.titleColors[title] = `hsl(${hue}, 85%, 50%)`; // 降低15%饱和度(从100%降到85%)
      }
      return this.titleColors[title];
    },
    
    hashCode(str) {
      let hash = 0;
      for (let i = 0; i < str.length; i++) {
        hash = str.charCodeAt(i) + ((hash << 5) - hash);
      }
      return hash;
    },
    
    getScheduleStyle(schedule) {
      const baseColor = this.getColorForTitle(schedule.title);
      const [h, s, l] = baseColor.match(/\d+/g);
      const textColor = l > 50 ? '#000' : '#fff';
      return {
        'background-color': baseColor,
        'color': textColor
      };
    }
  },
  
  watch: {
    schedules: {
      immediate: true,
      handler(newSchedules) {
        // 为所有标题预生成颜色
        newSchedules?.forEach(schedule => {
          this.getColorForTitle(schedule.title);
        });
      }
    }
  }
}
</script>

<style scoped>
.schedule-week-view {
  font-family: Arial, sans-serif;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.week-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
}

.nav-buttons {
  display: flex;
  gap: 10px;
}

.nav-button, .today-button {
  padding: 5px 10px;
  border: 1px solid #ccc;
  background-color: #fff;
  cursor: pointer;
  border-radius: 3px;
}

.today-button {
  background-color: #4285f4;
  color: white;
  border-color: #4285f4;
}

.week-range {
  font-weight: bold;
}

.week-header {
  display: grid;
  grid-template-columns: 80px repeat(7, 1fr);
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
}

.time-label, .day-header {
  padding: 8px;
  text-align: center;
  font-size: 14px;
}

.day-header.today {
  background-color: #e6f2ff;
}

.day-name {
  font-weight: bold;
}

.day-date {
  color: #666;
}

.time-grid {
  flex: 1;
  overflow-y: auto;
  display: grid;
  grid-template-columns: 80px repeat(7, 1fr);
  /* 隐藏滚动条但保留滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
}

.time-grid::-webkit-scrollbar {
  display: none; /* Chrome/Safari */
}

.time-row {
  display: contents;
}

.time-slot {
  grid-column: 1;
  padding: 5px;
  font-size: 12px;
  color: #666;
  text-align: right;
  border-bottom: 1px solid #eee;
}

.empty-slot {
  grid-column: 1;
  border-bottom: 1px solid #eee;
}

.grid-cell {
  border-left: 1px solid #eee;
  border-bottom: 1px solid #eee;
  min-height: 30px;
  position: relative;
}

.grid-cell.today {
  background-color: #f5f9ff;
}

.schedule-item {
  position: absolute;
  left: 2px;
  right: 2px;
  border-radius: 2px;
  padding: 2px 4px;
  font-size: 12px;
  overflow: hidden;
  transition: all 0.2s ease;
}

.schedule-title {
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.schedule-time {
  font-size: 11px;
}

@media (max-width: 768px) {
  .week-header {
    grid-template-columns: 60px repeat(7, 1fr);
  }
  
  .time-grid {
    grid-template-columns: 60px repeat(7, 1fr);
  }
  
  .time-slot {
    font-size: 11px;
  }
  
  .day-name, .day-date {
    font-size: 12px;
  }
}
</style>